//
//  purchaseView.m
//  tcpoctest
//
//  Created by gump on 6/18/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "purchaseView.h"
#import "SecurityUtil.h"
#import <QuartzCore/QuartzCore.h>

@implementation purchaseView

-(void)initUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createTitle];
    self.mtitle.text = @"充值";
    
    UIButton *pbtn = [[UIButton alloc] initWithFrame:CGRectMake(240, 70, 60, 44)];
    [pbtn setTitle:@"购买" forState:UIControlStateNormal];
    [pbtn setBackgroundColor: [UIColor blueColor]];
    
    [pbtn.layer setMasksToBounds:YES];
    [pbtn.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    [pbtn.layer setBorderWidth:1.0];   //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });
    [pbtn.layer setBorderColor:colorref];
    
    [pbtn addTarget:self action:@selector(topay) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pbtn];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回"
                                                                target:self
                                                                action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    
    UIImageView *coinview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 84, 24, 24)];
    coinview.image = [UIImage imageNamed:@"gold.png"];
    [self.view addSubview:coinview];
    
    UILabel *paylabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 80, 200, 30)];
    paylabel.backgroundColor = [UIColor clearColor];
    paylabel.text = @"6￥可以购买60万金币";
    [self.view addSubview:paylabel];
}

-(void)backButtonPressed
{
    [[ViewManager sharedViewManager] backView:self];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

-(void)pay
{
    [[ViewManager sharedViewManager] showView:VI_PURCHASE_SELECT
                             withIsRemoveCurV:false
                                withDirection:VD_NULL];
}

-(void)topay
{
        if ([SKPaymentQueue canMakePayments]) {
            [self getProductInfo];
        } else {
            NSLog(@"失败，用户禁止应用内付费购买.");
        }
}

- (void)getProductInfo {
    NSSet * set = [NSSet setWithArray:@[@"coin4"]];
    SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    request.delegate = self;
    [request start];
}

// 以上查询的回调函数
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *myProduct = response.products;
    if (myProduct.count == 0) {
        NSLog(@"无法获取产品信息，购买失败。");
        return;
    }
    SKMutablePayment * payment = [SKMutablePayment paymentWithProduct:myProduct[0]];
    payment.quantity = 1;
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
                NSLog(@"transactionIdentifier = %@", transaction.transactionIdentifier);
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed://交易失败
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored://已经购买过该商品
                [self restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
                NSLog(@"商品添加进列表");
                break;
            default:
                break;
        }
    }
    
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    // Your application should implement these two methods.
    NSString * productIdentifier = transaction.payment.productIdentifier;
    NSString * receipt = [SecurityUtil encodeBase64Data:transaction.transactionReceipt];
    
     NSLog(@"productIdentifier=%@\nreceipt=%@", productIdentifier, receipt);
    if ([productIdentifier length] > 0) {
        
        
        NSURL *url = [NSURL URLWithString:@"http://user.peng7.net/recharge/ios"];
        
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        
        [request setHTTPMethod:@"POST"];
        
        NSString *str = [NSString stringWithFormat:@"out_user=%@&receipt=%@&platform=001",
                         [DataControl shareControl].personDS.uinfo.mail
                         ,receipt];
        
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        [request setHTTPBody:data];
        
        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
        
        if (connection) {
            webdata = [[NSMutableData alloc] init];
        }
    }
    
    // Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"购买失败，请检查iTunes账号"
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        NSLog(@"用户取消交易");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    // 对于已购商品，处理恢复购买的逻辑
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data {
    
    [webdata appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConn {
    
    NSString *results = [[NSString alloc]
                         
                         initWithBytes:[webdata bytes]
                         
                         length:[webdata length]
                         
                         encoding:NSUTF8StringEncoding];
    
    NSLog(@"results=%@",results);
    
    if ([results isEqualToString:@"success"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"购买成功"
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"购买失败，请检查iTunes账号"
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
    webdata = nil;
    
}

@end
